package com.ldatum.crm.action.admin;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.ldatum.crm.domain.Admin;
import com.ldatum.crm.domain.User;
import com.ldatum.crm.service.UserService;
import com.ldatum.crm.serviceImpl.UserServiceImpl;
import com.ldatum.crm.util.MD5;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

@ParentPackage("admin")
@Results({ 
	@Result(name = "mainAction", location = "admin!main.action",type = "redirect")
})
public class UserAction extends BaseAction{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String loginname;//页面返回的登录名称
	private String password; //页面返回的密码
	private String fullname;//用户姓名
	private String email;
	private String address;
	private String city;
	private String role;
	private String gender;
	private String storename;
	private String status;
	private String remarks;
	private String telephone;
	private String time;
	
	private String ids;//批量选中的id
	
	private String alertMessage;
	
	private String opwd;
	private String npwd;
	private String rnpwd;
	private int id;
	
	
	
	private User user = new User();//用户类
	
	private UserService userService = new UserServiceImpl();

	private List<User> userList = new ArrayList<User>();

	
	/**
	 * 
	 * 描述 : 返回登录界面
	 * @return
	 */
	public String login(){
		return "index";
	}
	
	/**
	 * 
	 * 描述 : 实现登录，用户名密码正确则跳转到主界面，否则提示并返回返回到登录界面. <br>
	 * @return
	 * @throws Exception
	 */
	@InputConfig(resultName = "index")
	public String doLogin() throws Exception{
		if("".equals(loginname) | "".equals(password)){
			alertMessage = "用户名和密码不能为空";
			return "index";
		}
		User u = userService.query(loginname);
		if (u == null){
			alertMessage = "用户名不存在";
			return "index";
		}
		if(u.getStatus().equals("停用")){
			alertMessage = "用户名是停用状态，请联系管理员";
			return "index";
		}
		if (MD5.md5(password).equals(u.getPassword())) {
			setSession(Admin.LOGIN_EMPLOYEE_ID, u.getId());
			setSession(Admin.LOGIN_EMPLOYEE_ID_SESSION_NAME,u.getId());
			setSession(Admin.LOGIN_EMPLOYEE_USERNAME_COOKIE_NAME,u.getFullname());
			setSession(Admin.LOGIN_EMPLOYEE_ROLE_NAME,u.getRole());
			return "mainAction";
		}else{
			alertMessage = "密码错误";
			return "index";
		}
	}
	/**
	 * 
	 * 描述 : <描述函数实现的功能>. <br>
	 * @throws Exception 
	 */
	public void save() throws Exception{
		User u = new User();
		u.setId(id);
		u.setAddress(address);
		u.setCity(city);
		u.setEmail(email);
		u.setFullname(fullname);
		u.setPassword(password);
		u.setGender(gender);
		u.setLoginname(loginname);
		u.setRemarks(remarks);
		u.setRole(role);
		u.setStatus(status);
		u.setStore(storename);
		u.setPhone(telephone);
		u.setTime(time);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("type/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out;
		out = response.getWriter();
		JSONObject json = new JSONObject();
		int result;
		boolean b = userService.validationLoginname(loginname);
		if(b){
			result = userService.update(u);
		}else{
			result = userService.save(u);
		}
		if(result==1){
			json.accumulate("success", true);
		}else{
			json.accumulate("success", false);
		}
		out.println(json.toString());
		out.flush();
		out.close();
	}
	
	public String signup() throws Exception{
		User u = new User();
		u.setAddress(address);
		u.setCity(city);
		u.setEmail(email);
		u.setFullname(fullname);
		u.setPassword(password);
		u.setLoginname(loginname);
		u.setRemarks(remarks);
		u.setRole("操作员");
		u.setStatus("启用");
		u.setStore("");
		u.setPhone(telephone);
		u.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
		int result;
		boolean b = userService.validationLoginname(loginname);
		if(b){
			alertMessage = "注册失败,用户名已存在,请重试!";
			return "index";
		}else{
			result = userService.save(u);
			if(result==1){
				setSession(Admin.LOGIN_EMPLOYEE_ID, u.getId());
				setSession(Admin.LOGIN_EMPLOYEE_ID_SESSION_NAME,u.getId());
				setSession(Admin.LOGIN_EMPLOYEE_USERNAME_COOKIE_NAME,u.getFullname());
				setSession(Admin.LOGIN_EMPLOYEE_ROLE_NAME,u.getRole());
				return "mainAction";
			}else{
				alertMessage = "注册失败,网络异常,请重试!";
				return "index";
			}
		}
	}
	
	/**
	 * 
	 * 描述 : 退出登录操作. <br>
	 * @return 
	 */
	public String logout() {
		getRequest().getSession().removeAttribute(Admin.LOGIN_EMPLOYEE_ID);
		return LOGIN;
	}
	/**
	 * 
	 * 描述 : 用户密码忘记了,像注册邮箱发送邮件. <br>
	 * @return
	 */
	public void forgetPasswd(){
		
	}
	
	
	/**
	 * 
	 * 描述 : 用户从主界面回到登录界面，并删除用户session. <br>
	 * @return
	 */
	public String  lock(){
		getRequest().getSession().removeAttribute(Admin.LOGIN_EMPLOYEE_ID);
		return "lock";
	}
	/**
	 * 修改密码
	 * @return
	 * @throws Exception 
	 */
	public void changePasswd() throws Exception{
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("type/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out;
			out = response.getWriter();
			JSONObject json = new JSONObject();
			boolean b = userService.validationPwd(id,opwd);
			if(b){
				int result = userService.updatePwd(id,npwd);
				if(result>=1){
					json.accumulate("result", true);
				}else{
					json.accumulate("result", false);
				}
			}else{
				json.accumulate("result", false);
			}
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * 描述 : <重置密码>. <br>
	 * @throws Exception
	 */
	public void resetPasswd() throws Exception{
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("type/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out;
			out = response.getWriter();
			JSONObject json = new JSONObject();
			int result = userService.updatePwd(id,npwd);
			if(result>=1){
				json.accumulate("result", true);
			}else{
				json.accumulate("result", false);
			}
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * 描述 : 增加用户信息
	 * @return
	 */
	public String add(){
		
		return "addUser";
	}
	
	public void deletes(){
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("type/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out;
			out = response.getWriter();
			JSONObject json = new JSONObject();
			int result  = userService.deletes(ids);
			if(result<1){
				json.accumulate("success", false);
			}else{
				json.accumulate("success", true);
			}
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 编辑用户信息
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception{
		System.out.println(id+"...................ssss");
		user = userService.findById(id);
		
		return "addUser";
	}
	
	/**
	 * 更新用户状态
	 */
	public void updateStatusToStart(){
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("type/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out;
			out = response.getWriter();
			JSONObject json = new JSONObject();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
			int result  = userService.updateStatusToStart(ids);
			if(result<1){
				json.accumulate("success", false);
			}else{
				json.accumulate("success", true);
			}
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void updateStatusToStoping(){
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("type/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out;
			out = response.getWriter();
			JSONObject json = new JSONObject();
			int result  = userService.updateStatusToStoping(ids);
			if(result<1){
				json.accumulate("success", false);
			}else{
				json.accumulate("success", true);
			}
			out.println(json.toString());
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public String list() throws SQLException{
		userList  = userService.list();
		return "listUser";
	}

	public String getLoginname() {
		return loginname;
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFullname() {
		return fullname;
	}

	public void setFullname(String fullname) {
		this.fullname = fullname;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getStorename() {
		return storename;
	}

	public void setStorename(String storename) {
		this.storename = storename;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getRemarks() {
		return remarks;
	}

	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getAlertMessage() {
		return alertMessage;
	}

	public void setAlertMessage(String alertMessage) {
		this.alertMessage = alertMessage;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public String getOpwd() {
		return opwd;
	}

	public void setOpwd(String opwd) {
		this.opwd = opwd;
	}

	public String getNpwd() {
		return npwd;
	}

	public void setNpwd(String npwd) {
		this.npwd = npwd;
	}

	public String getRnpwd() {
		return rnpwd;
	}

	public void setRnpwd(String rnpwd) {
		this.rnpwd = rnpwd;
	}
}
